package com.erp.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.activiti.engine.repository.ProcessDefinition;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.erp.dao.ProcessDeploymentDAO;
import com.erp.domain.TProcessDeployment;
import com.erp.domain.TUser;
import com.erp.dto.ProcessDeployment;
import com.erp.dto.User;

@Service(value = "procDepService")
@Transactional
public class ProcessDeploymentService {

	@Resource(name = "procDepDAO")
	ProcessDeploymentDAO procDepDAO;

	/**
	 * 挂起某key的流程定义
	 * 
	 * @param key
	 */
	public void suspendProcDepByKey(String key) {
		String hql = "from TProcessDeployment t where t.key = '" + key + "'";
		TProcessDeployment tProcDep = procDepDAO.get(hql);
		tProcDep.setState(0);
	}

	/**
	 * 激活某key的流程定义
	 * 
	 * @param key
	 */
	public void activateProcDepByKey(String procDefKey) {
		String hql = "from TProcessDeployment t where t.key = '" + procDefKey
				+ "'";
		TProcessDeployment tProcDep = procDepDAO.get(hql);
		tProcDep.setState(1);
	}

	/**
	 * 根据流程实例ID获取ProcessDeployment对象
	 * 
	 * @param model
	 * @return
	 */
	@Deprecated
	public ProcessDeployment getProcDepByInstId(String procInstId) {
		String hql = "from TProcessDeployment t where t.procInstId = '"
				+ procInstId + "'";
		TProcessDeployment tProcDep = procDepDAO.get(hql);
		return new ProcessDeployment(tProcDep);
	}

	/**
	 * 列出所有已部署的流程定义
	 * 
	 * @return
	 */
	public List<ProcessDeployment> listProcDef() {
		List<TProcessDeployment> tProcDepList = procDepDAO.listAll();
		List<ProcessDeployment> procDepList = null;
		if (tProcDepList.size() > 0) {
			procDepList = new ArrayList<ProcessDeployment>();
			for (TProcessDeployment tProcDep : tProcDepList) {
				procDepList.add(new ProcessDeployment(tProcDep));
			}
		}
		return procDepList;
	}

	public void add(ProcessDefinition procDef, User deployUser) {
		String hql = "from TProcessDeployment t where t.key = '"
				+ procDef.getKey() + "'";
		TProcessDeployment tProcDep = procDepDAO.get(hql);
		if (tProcDep == null) {
			// 如果数据库里不存在该流程定义的key，则新增TProcessDeployment对象
			tProcDep = new TProcessDeployment(procDef);
			tProcDep.settDeployUser(new TUser(deployUser));
			procDepDAO.save(tProcDep);
		} else {
			// 若存在，则修改TProcessDeployment对象
			tProcDep.setVersion(procDef.getVersion());
			tProcDep.setProcDefId(procDef.getId());
			tProcDep.setName(procDef.getName());
			tProcDep.setDescription(procDef.getDescription());
			tProcDep.setDeployTime(new Date());
		}
	}

	public void deleteByKey(String key) {
		String hql = "from TProcessDeployment t where t.key = '" + key + "'";
		TProcessDeployment tProcDep = procDepDAO.get(hql);
		if (tProcDep != null) {
			procDepDAO.delete(tProcDep);
		}
	}

}
